package com.aiden.app.common.util

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.aiden.app.common.R
import com.aiden.app.common.base.BaseApplication
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.modelmsg.SendAuth



/**
 *
 * 微信分享工具类
 * @author yanggeng
 * @date 2019/1/2 下午5:23
 */
object WechatUtils {
    val SHARE_TO_FRIEND = SendMessageToWX.Req.WXSceneSession
    val SHARE_TO_TIMELINE = SendMessageToWX.Req.WXSceneTimeline

    private var wxapi = BaseApplication.INSTANCE.getWXApi()
    private val THUMB_SIZE = 56
    private val TYPE_WEBPAGE = "webpage"
    private val TYPE_TEXT = "text"
    private val TYPE_IMAGE = "img"

    /**
     * 分享连接到微信
     *
     * @param context
     * @param url 分享连接
     * @param title 标题
     * @param content 简介
     * @param imgId 分享图标
     * @param scene 分享渠道，[SHARE_TO_FRIEND]为分享到给好友，[SHARE_TO_TIMELINE]为分享到朋友圈
     */
    fun shareWebPage(context: Context, url: String, title: String, content: String, imgId: Int = R.mipmap.app_logo, scene: Int) {
        val webpageObject = WXWebpageObject()
        webpageObject.webpageUrl = url
        val mediaMessage = WXMediaMessage(webpageObject)
        mediaMessage.title = title
        mediaMessage.description = content
        mediaMessage.setThumbImage(BitmapFactory.decodeResource(context.resources, imgId))

        wxapi.sendReq(createReq(TYPE_WEBPAGE, mediaMessage, scene))
    }

    /**
     * 分享图片
     *
     * @param bmp 分享图片bitmap对象
     * @param scene
     */
    fun shareImage(bmp: Bitmap, scene: Int) {
        val imageObject = WXImageObject(bmp)
        val mediaMessage = WXMediaMessage(imageObject)

        // 缩略图
        val thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true)
        bmp.recycle()
        mediaMessage.setThumbImage(thumbBmp)

        wxapi.sendReq(createReq(TYPE_IMAGE, mediaMessage, scene))
    }

    /**
     * 分享文本
     */
    fun shareText(text: String, scene: Int) {
        val textObject = WXTextObject(text)
        val mediaMessage = WXMediaMessage(textObject)
        mediaMessage.description = text
        wxapi.sendReq(createReq(TYPE_TEXT, mediaMessage, scene))
    }

    fun login() {
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo" // 应用授权作用域，如获取用户个人信息则填写snsapi_userinfo
        req.state = "dahu_wx_login" // 用于保持请求和回调的状态，该字段应自定义，用于区分不同请求，如微信登录和绑定
        wxapi.sendReq(req)
    }

    private fun createReq(type: String, message: WXMediaMessage, scene: Int): SendMessageToWX.Req {
        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction(type)
        req.message = message
        req.scene = scene
        return req
    }

    private fun buildTransaction(type: String): String {
        return type + System.currentTimeMillis()
    }
}